import type { Iroutes } from "../router"
import { useLayoutEffect, Fragment, ReactNode, Suspense } from "react"
import { useRoutes, useNavigate, useLocation } from "react-router-dom"
//Fragment是一个虚拟容器组件,不会渲染到页面上,只是作为一个容器使用
//声明类型
type Iguard = (tokenKey: string, routes: Iroutes, fallback?: ReactNode) => ReactNode

//自定义hook一般会约定以use开头

let useRouterWithGuard: Iguard = (tokenKey, routes, fallback = (<h1>正在加载...</h1>)) => {
    console.log(routes[0].element)
    //是否有token,有token就通过,没有token直接返回登入页
    //获取token
    let token = sessionStorage.getItem(tokenKey);
    //如果有token,就返回routes,没有就返回登入页
    let element = useRoutes(routes)
    //路由跳转的hook
    let navigate = useNavigate()
    //location对象
    let location = useLocation()
    //根据路径进行判断
    useLayoutEffect(() => {
        //如果没有token,访问的不是登入页,那么就要跳转到登入页

        //如果没有token,访问的是登入页,那么直接通过就行
        if (!token) {
            //没有token
            if (location.pathname !== "/login") {
                navigate("/login")
            }
        }

    }, [location.pathname])

    return (<Fragment>
        <Suspense fallback={fallback}>
            {element}
        </Suspense>
    </Fragment>)

}


export default useRouterWithGuard